package com.bdqn.miaoshaconsumer.service;

import com.bdqn.miaoshaconsumer.entity.Product;
import com.bdqn.miaoshaconsumer.entity.ProductRecord;
import com.bdqn.miaoshaconsumer.mapper.ProductMapper;
import com.bdqn.miaoshaconsumer.mapper.ProductRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "MiaoshaQueue")
public class DirectReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(DirectReceiver.class);
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProductRecordMapper productRecordMapper;

    @RabbitHandler(isDefault = true)
    public void process(Map ReceiveMessage) {
        System.out.println("消费者DirectReceiver收到消息" + ReceiveMessage.get("messageData"));
        Integer userId = Integer.valueOf(ReceiveMessage.get("messageData").toString());
        Product product = productMapper.findByProductNO("101");
        if (product != null && product.getTotal() > 0) {
            product.setTotal(product.getTotal() - 1);
            int i = productMapper.updateById(product);
            if (i > 0) {
                productRecordMapper.insert(new ProductRecord("101", userId));
                LOGGER.info("用户{}抢单成功", userId);
            } else {
                LOGGER.error("用户{}抢单失败", userId);
            }
        } else {
            LOGGER.error("用户{}抢单失败", userId);
        }
    }
}
